package com.wuwei.elearning.question.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuwei.elearning.question.domain.Chapter;
import com.wuwei.elearning.question.domain.Subject;
import com.wuwei.elearning.question.mapper.ChapterMapper;
import com.wuwei.elearning.question.mapper.SubjectMapper;
import com.wuwei.elearning.question.service.SubjectService;
import com.wuwei.elearning.vo.SubjectVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuwei
 * @since 2024-02-01
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {


    @Resource
    private SubjectMapper subjectMapper;

    @Resource
    private ChapterMapper chapterMapper;

    /**
     * 获取满足vant要求的数据结构
     *    options: [
     *         {
     *           text: '浙江省',
     *           value: '330000',
     *           children: [{ text: '杭州市', value: '330100' }],
     *         },
     *         {
     *           text: '江苏省',
     *           value: '320000',
     *           children: [{ text: '南京市', value: '320100' }],
     *         },
     *       ],
     * @return
     */
    @Override
    public List<SubjectVo>  getTree() {
        LambdaQueryWrapper<Subject> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Subject::getName,"R3").or().eq(Subject::getName,"综合阅读");
        List<Subject> subjects = subjectMapper.selectList(wrapper);
        List<SubjectVo> list = new ArrayList<>();
        subjects.forEach(subject -> {
            SubjectVo vo = new SubjectVo();
            Long id = subject.getId();
            String name = subject.getName();
            vo.setValue(id);
            vo.setText(name);
            //查询其孩子，也就是章节
            List<SubjectVo> children  = getChildren(id);
            vo.setChildren(children);
            list.add(vo);
        });
        return list;
    }

    private List<SubjectVo> getChildren(Long id) {
        List<SubjectVo> children  = new ArrayList<>();

        LambdaQueryWrapper<Chapter> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Chapter::getSubjectId,id);
        List<Chapter> chapters = chapterMapper.selectList(wrapper);

        chapters.forEach(chapter -> {
            Long chapterId = chapter.getId();
            String chapterName = chapter.getName();
            SubjectVo vo = new SubjectVo();
            vo.setText(chapterName);
            vo.setValue(chapterId);
            children.add(vo);
        });

        return children;
    }
}
